//
//  ExtractCoinView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/14.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class ExtractCoinView: BaseView, UITableViewDelegate, UITableViewDataSource {
    var viewModel:ExtractCoinViewModel?
    var selectIndex:Int?
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 100))
        return view
    }()
    lazy var addressBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "addAddress"), for: .normal)
        btn.setTitle("  " + kText("添加地址"), for: .normal);
        btn.setTitleColor(UIColor(hexStr: "#4671fe"), for: .normal)
        btn.addTarget(self, action: #selector(addressAction), for: UIControlEvents.touchUpInside)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return btn
    }()
   
    override func setUpUI() {
        super.setUpUI()
        viewModel = self.dataSource as? ExtractCoinViewModel
        
        viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(isiPhoneX() ? -83 : -49)
        }
        
        self.addSubview(addressBtn)
        addressBtn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(isiPhoneX() ? -34 : 0 )
            make.height.equalTo(49)
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
        }
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            tableView.reloadData()
        }
        
    }
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return (viewModel?.dataArr.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identyCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? BaseTableViewCell
        if cell == nil {
            cell = BaseTableViewCell(style: .default, reuseIdentifier: identy)
            cell?.setArrowImage()
            cell?.contentView.addSubview((cell?.kindLabel)!)
            cell?.kindLabel.numberOfLines = 0
             cell?.contentView.addSubview((cell?.kindLabel)!)
            cell?.kindLabel.snp.makeConstraints { (make) in
                make.top.equalTo((cell?.nameLabel.snp.bottom)!).offset(15)
                make.left.equalToSuperview().offset(40)
                make.right.equalToSuperview().offset(-40)
            }
            cell?.nameLabel.numberOfLines = 0
            cell?.nameLabel.snp.remakeConstraints { (make) in
                make.top.equalToSuperview().offset(25)
                make.left.equalToSuperview().offset(40)
                make.right.equalToSuperview().offset(-40)
            }
            
            cell?.contentView.addSubview((cell?.iconImage)!)
            cell?.iconImage.image = UIImage(named: "adLocation")
            cell?.iconImage.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.top.equalToSuperview().offset(24)
            }
            cell?.selectionStyle = .none
        }
        let model = viewModel?.dataArr[indexPath.section]
        cell?.nameLabel.text = model?.drawAdd.count != 0 ? model?.drawAdd : ""
        
        cell?.kindLabel.text = model?.remarks.count != 0 ? model?.remarks : ""
       
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = viewModel?.dataArr[indexPath.section]
        return 70 + (model?.height)! 
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 0.1))
        view.backgroundColor = UIColor.clear
        return view
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (viewModel?.selectBool)! {
            let model = viewModel?.dataArr[indexPath.section]
            NotificationCenter.default.post(name: NSNotification.Name.Exchange.addressDidSelect, object: model)
            for popView in ((self.viewModel?.controller?.navigationController as! WrapNavigationController).wrapViewController?.navigationController?.viewControllers)! {
                let viewController = (popView as? WrapViewController)?.contentViewController
                if (viewController?.isKind(of: SendCoinViewController.self))! {
                    self.viewModel?.controller?.navigationController?.popToViewController(viewController!, animated: true)
                    return
                }
            }
            self.viewModel?.controller?.navigationController?.popToRootViewController(animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        Alert.default.show(title: "", message: kText("是否删除当前地址?"), actions: [kText("取消"),kText("确认")], from: (viewModel?.controller)!, completion: nil)
        Alert.default.delegate = self
        selectIndex = indexPath.section
    }
    
    @objc func addressAction() {
        let controller = AddAddressViewController()
        controller.viewModel?.coinCode = (viewModel?.coinCode)!
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension ExtractCoinView:AlertDelegate {
    func alert(didSelected title: String?) {
        if title == kText("确认") {
            let model = viewModel?.dataArr[selectIndex!]
            viewModel?.drawAdd = (model?.drawAdd)!
            viewModel?.delectAddress()
        }
    }
}
